package com.corticon.dialogs.dao.hibernate;

import static org.hibernate.criterion.Restrictions.*;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;

import org.springframework.stereotype.Repository;

import com.corticon.dialogs.dao.UserGroupDAO;
import com.corticon.dialogs.model.UserGroup;
import com.corticon.dialogs.util.Pager;

/**
 *
 * @author Lifan Yang
 */
@Repository("userGroupDAO")
public class UserGroupHibernateDAO extends GenericHibernateDAO<UserGroup, String> implements
    UserGroupDAO {

    @Override
    public long getCountByCriteria(String criteria) {
        Criteria c = this.getBaseCriteria();
        criteria = "%" + criteria + "%";
        if (!criteria.equals("")) {
            c.add(disjunction().add(like("name", criteria)).add(like("contactName", criteria)).
                add(like("contactEmail", criteria)));
        }
        return this.getCount(c);
    }

    @Override
    public List<UserGroup> getPageOfUserGroups(String criteria) {
        Criteria c = this.getBaseCriteria();
        criteria = "%" + criteria + "%";
        if (!criteria.equals("")) {
            c.add(disjunction().add(like("name", criteria)).add(like("contactName", criteria)).
                add(like("contactEmail", criteria)));
        }
        return c.list();
    }

    @Override
    public long getSearchCount(String keywords) {
        return getCount(buildSearchCriteria(keywords));
    }

    @Override
    public List<UserGroup> search(String keywords, Pager pager) {
        return getPageOfData(buildSearchCriteria(keywords), pager);
    }

    private Criteria buildSearchCriteria(String keywords) {
        Criteria searchCriteria = getBaseCriteria();

        if (StringUtils.isNotBlank(keywords)) {
            keywords = keywords.trim();
            searchCriteria.add(disjunction().add(ilike("name", keywords, MatchMode.ANYWHERE)).add(
                ilike("contactName", keywords, MatchMode.ANYWHERE)).add(ilike("contactEmail", keywords,
                MatchMode.ANYWHERE)).add(ilike("description", keywords, MatchMode.ANYWHERE)));
        }

        return searchCriteria;
    }
}
